var appointTimeId="";
$(document).ready(function() {
	$("#addProject").click(function(){
		$("#btn").text("提交");
		displayPlan($('option').eq(0).val());
		$("#planSelect").val($('option').eq(0).val());
		$("#startDate").val("");
		$("#endDate").val("")
	});
	$.ajax({
		async:false,
		url :Server + "/time/projectTime/myPlanList",
		//url :"http://localhost/time/projectTime/myPlanList",
		data : {
			"uid":$("#useridoflogin").val()
			//"uid": "4d272484d5844be693c05443c4edd71e"
		},
		type : "POST",
		dataType: "JSON",
		success : function(data) {
			var options=""
			if(data.length>=1){
				for(var i = 0; i < data.length; i++){
					options+='<option value='+data[i].projectId+'>'+data[i].timeName+'</option>'
				}
				$("#planSelect").html(options);
				displayPlan(data[0].projectId);
				$("#planSelect").change(function(){
					displayPlan($("#planSelect").val());
				});
			}else if(data.length==0){
				$("#timeTable").hide();
				$("#btn").hide();
				$('select option').remove();
			}
			myProjectList();
			if(GetUrlByParamName("insId")==undefined){
				$("#adoptProject").css('display','none'); 
			}
			$("#adoptProject").click(function() {
				if($(".row label img[src$='images/icon36.png']").length==0){
					alert("请选择一个周计划");
					return;
				}else if($(".row label img[src$='images/icon36.png']").length>1){
					alert("仪器只能应用一个周计划");
					return;
				}else if($(".row label img[src$='images/icon36.png']").length==1){
					$.ajax({
						async:false,
						url :Server + "/time/projectTime/insAdoptProject",
						//url :"http://localhost/time/projectTime/insAdoptProject",
						data : {
							"appointTimeId":$(".row label img[src$='images/icon36.png']").eq(0).parent().parent().attr("val"),
							"insId":GetUrlByParamName("insId")
						},
						type : "POST",
						//dataType: "JSON",
						success : function(data) {
							alert(data);
							window.location.href="publishInstrument17";
						}
					});
				}
			});
			$("#deleteProject").click(function() {
				var idStr="";
				$(".row label img[src$='images/icon36.png']").each(function() {
					idStr=idStr+$(this).parent().parent().attr("val")+",";
				});
				if(idStr==""){
					alert("请至少选择一条删除");
				}else {
					idStr=idStr.substring(0,idStr.length-1);
					$.ajax({
						async:false,
						url :Server + "/time/projectTime/deleteInsProject",
						//url :"http://localhost/time/projectTime/deleteInsProject",
						data : {
							"idStr":idStr
						},
						type : "POST",
						//dataType: "JSON",
						success : function(data) {
							alert(data);
							window.location.reload();
						}
					});
				}
			});
		}
	});
	
});	
var daysMap = {};
function displayPlan(projectId) {
	$.ajax({
		async:false,
		url :Server + "/time/projectTime/displayPlan",
		//url :"http://localhost/time/projectTime/displayPlan",
		type : "POST",
		dataType : "JSON",
		data  : {
			"projectId":projectId
		},
		success : function(data) {
			var tableHead='<tr>\
			<th>时间</th>';
			for(var i = 0; i < data.length; i++){
				tableHead+='<th class="'+data[i].timeId+'">\
					<input type="checkbox" name="" id="" value="" />\
					<label>\
					<img src="images/icon35.png"/>\
					<span>'+data[i].startTime+'：00-'+data[i].endTime+':00</span>\
				</label>\
				</th>';
			}
			var tableBody="";
			for(var x = 0; x < 7; x++){
				tableBody+='<tr><td>\
					<input type="checkbox" name="" id="" value="" />\
					<label>\
					<img src="images/icon35.png"/>\
					<span>#1</span>\
				</label>\
				</td>';
				var weekDay="";
				switch(x){
				case 0:
					weekDay="周一";
				    break;
				case 1:
					weekDay="周二";
				    break;
				case 2:
					weekDay="周三";
				    break;
				case 3:
					weekDay="周四";
				    break;
				case 4:
					weekDay="周五";
				    break;
				case 5:
					weekDay="周六";
				    break;
				case 6:
					weekDay="周日";
				    break;
				}
				tableBody=tableBody.replace("#1",weekDay);
				for(var j = 0; j < data.length; j++){
					tableBody+='<td class="'+data[j].timeId+'">\
						<input type="checkbox" name="" id="" value="" />\
						<label>\
						<img src="images/icon35.png"/>\
					</label>\
					</td>';				
				}
				tableBody+='</tr>';
			}
			$("#timeTable").html(tableHead+tableBody);
			$("table label").click(function() {
				if($(this).siblings('input').is(':checked')) {
					//取消选中
					$(this).find('img').attr('src', 'images/icon35.png');
					$(this).siblings('input').prop('checked', false);
				} else {
					//选中
					$(this).find('img').attr('src', 'images/icon36.png');
					$(this).siblings('input').prop('checked', true);
					
				};
			});

			$('#btn').unbind("click");
			$("#btn").click(function() {
				daysMap= {};
				for(var j = 0; j < data.length; j++){
					var dayStr="";
					$("."+data[j].timeId+"").each(function() {
						if($(this).children().eq(1).children().eq(0).attr("src")=="images/icon36.png"){
							dayStr=dayStr+wordToNum($(this).parent().children().eq(0).children().eq(1).children().eq(1).text())+",";
							//wordToNum($(this).parent().children().eq(0).children().eq(1).children().eq(1).text());
						}
					});	
					dayStr=dayStr.substring(0,dayStr.length-1);
					daysMap[data[j].timeId] = dayStr;
				}
				var daysJson = JSON.stringify(daysMap);
				if($("#btn").text()=="提交"){
					//alert(daysJson)
					$.ajax({
						url :Server + "/time/projectTime/addWeekProject",
						//url :"http://localhost/time/projectTime/addWeekProject",
						data : {
							"startDate":$("#startDate").val(),
							"endDate":$("#endDate").val(),
							"daysJson":daysJson,
							"projectId":$("#planSelect").val(),
							"uid":$("#useridoflogin").val()
							//"uid": "4d272484d5844be693c05443c4edd71e"
						},
						type : "POST",
						//dataType: "JSON",
						success : function(data) {
							alert(data);
							daysMap = {};
							window.location.reload();
						},
						error:function(data) {
							daysMap= {};
						}
					});
				}else if($("#btn").text()=="保存"){
					//alert(daysJson)
					$.ajax({
						url :Server + "/time/projectTime/updateWeekProject",
						//url :"http://localhost/time/projectTime/updateWeekProject",
						data : {
							"startDate":$("#startDate").val(),
							"endDate":$("#endDate").val(),
							"daysJson":daysJson,
							"projectId":$("#planSelect").val(),
							"appointTimeId":appointTimeId,
							"uid":$("#useridoflogin").val()
							//"uid": "4d272484d5844be693c05443c4edd71e"
						},
						type : "POST",
						//dataType: "JSON",
						success : function(data) {
							alert(data);
							//window.location.reload();
							location.replace(location.href);
						},
						error:function(data) {
							alert("err")
							daysMap= {};
						}
					});
				}
			});
			
		},
	})
}

function myProjectList(){
	$.ajax({
		async:false,
		url :Server + "/time/projectTime/myProjectList",
		//url :"http://localhost/time/projectTime/myProjectList",
		data : {
			"uid":$("#useridoflogin").val()
			//"uid": "4d272484d5844be693c05443c4edd71e"
		},
		type : "POST",
		dataType: "JSON",
		success : function(data) {
			var html="";
			var row='<div val="#3" start="#4" end="#5" class="row">\
				<input type="checkbox" name="" id="" value="" />\
				<label><img src="images/icon35.png"/><span proId="#6">#1-#2</span></label>\
			</div>';
			for(var i = 0; i < data.length; i++){
				html+=row.replace("#1",new Date(data[i].startTime).Format("yyyy.MM.dd"))
				.replace("#2",new Date(data[i].endTime).Format("yyyy.MM.dd"))
				.replace("#3",data[i].id)
				.replace("#4",data[i].startTime)
				.replace("#5",data[i].endTime)
				.replace("#6",data[i].projectId)
			}
			$("#projectDiv").prepend(function(n){
			    return html;
			});
			$(".wrap .aside .aside_content .row label span").click(function() {
				$(".wrap .aside .aside_content .row label span").css('color','#ff8a00');
				$(this).css('color','#202020');
				appointTimeId=$(this).parent().parent().attr("val");
				$("#btn").text("保存");
				$("#startDate").val(new Date($(this).parent().parent().attr("start")).Format("yyyy-MM-dd"));
				$("#endDate").val(new Date($(this).parent().parent().attr("end")).Format("yyyy-MM-dd"))
				displayPlan($(this).attr("proId"));
				$("#planSelect").val($(this).attr("proId"));
				displayProject($(this).parent().parent().attr("val"));
			});
			$(".row label img").click(function() {
				if($(this).attr("src")=="images/icon36.png"){
					$(this).attr("src","images/icon35.png");
				}else if($(this).attr("src")=="images/icon35.png"){
					$(this).attr("src","images/icon36.png")
				}
			});
		}
	});
}

function displayProject(id) {
	$.ajax({
		url :Server + "/time/projectTime/displayProject",
		//url :"http://localhost/time/projectTime/displayProject",
		type : "POST",
		//async:false,
		dataType : "JSON",
		data  : {
			"id":id
		},
		success : function(data) {
			for(var i = 0; i < data.length; i++){
				var array = new Array();
				if(data[i].hasOwnProperty("monday")&&data[i].monday=="1"){
					array.push(1)
				}
				if(data[i].hasOwnProperty("tuesday")&&data[i].tuesday=="1"){
					array.push(2)
				}
				if(data[i].hasOwnProperty("wednesday")&&data[i].wednesday=="1"){
					array.push(3)
				}
				if(data[i].hasOwnProperty("thursday")&&data[i].thursday=="1"){
					array.push(4)
				}
				if(data[i].hasOwnProperty("friday")&&data[i].friday=="1"){
					array.push(5)
				}
				if(data[i].hasOwnProperty("saturday")&&data[i].saturday=="1"){
					array.push(6)
				}
				if(data[i].hasOwnProperty("sunday")&&data[i].sunday=="1"){
					array.push(7)
				}
				for(j = 0,len=array.length; j < len; j++) {
					$('.'+data[i].timeId+'').eq(array[j]).children().eq(1).children().eq(0).attr("src","images/icon36.png");   
				}
			}
			daysMap = {};
		},
	})
}

function bindClick(){
	$("table label").click(function() {
		if($(this).siblings('input').is(':checked')) {
			$(this).find('img').attr('src', 'images/icon35.png');
			$(this).siblings('input').prop('checked', false);
		} else {
			$(this).find('img').attr('src', 'images/icon36.png');
			$(this).siblings('input').prop('checked', true);
		};
	});
	$(".wrap .aside .aside_content .row label").click(function() {
		if($(this).siblings('input').is(':checked')) {
			$(this).find('img').attr('src', 'images/icon35.png');
			$(this).siblings('input').prop('checked', false);
			$(this).find('span').css('color','#ff8a00');
		} else {
			$(this).find('img').attr('src', 'images/icon36.png');
			$(this).siblings('input').prop('checked', true);
			$(this).find('span').css('color','#202020');
		};
	});
}

function wordToNum(word){
	switch(word){
	case "周一":
		return 1;
	    break;
	case "周二":
		return 2;
	    break;
	case "周三":
		return 3;
	    break;
	case "周四":
		return 4;
	    break;
	case "周五":
		return 5;
	    break;
	case "周六":
		return 6;
	    break;
	case "周日":
		return 7;
	    break;
	}
}

Date.prototype.Format = function(fmt){
	var o = {
		"M+": this.getMonth() + 1, //月份 
			"d+": this.getDate(), //日 
		"h+": this.getHours(), //小时 
		"m+": this.getMinutes(), //分 
		"s+": this.getSeconds(), //秒 
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
		"S": this.getMilliseconds() //毫秒 
	};
	if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for(var k in o)
	if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

function GetUrlByParamName(name) {
		 var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	 var URL =  decodeURI(window.location.search);
		 var r = URL.substr(1).match(reg);
	 if(r!=null){
        //decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码
         return decodeURI(r[2]);
		 };
	     return null;
};